package library

import (
	"bytes"
	"errors"
	"io"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"
)

type RequestLibrary struct {
	url     string
	Headers map[string]string
}

type RequestLibraryOption func(*RequestLibrary)

func NewRequestLibrary(option ...RequestLibraryOption) *RequestLibrary {
	r := &RequestLibrary{
		url:     "",
		Headers: make(map[string]string),
	}
	for _, libraryOption := range option {
		libraryOption(r)
	}
	return r
}

func (r *RequestLibrary) Get() (*http.Response, error) {
	request, err := http.NewRequest(http.MethodGet, r.url, nil)
	if err != nil {
		return nil, err
	}
	for k, v := range r.Headers {
		request.Header.Set(k, v)
	}
	client := &http.Client{}
	return client.Do(request)
}

func WithHeaders(headers map[string]string) RequestLibraryOption {
	return func(library *RequestLibrary) {
		library.Headers = headers
	}
}

func WithUrl(u string) RequestLibraryOption {
	return func(r *RequestLibrary) {
		r.url = u
	}
}

func Get(url string) ([]byte, error) {
	client := http.Client{}
	response, err := client.Get(url)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()
	if response.StatusCode != http.StatusOK {
		return nil, errors.New("状态码不为200")
	}

	data, err := io.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}
	return data, nil
}

// UploadFile 上传文件
func (r *RequestLibrary) UploadFile(filePath string) (*http.Response, error) {
	f, err := os.Open(filePath)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	part, err := writer.CreateFormFile("file", filepath.Base(filePath))
	if err != nil {
		return nil, err
	}
	_, err = io.Copy(part, f)
	if err != nil {
		return nil, err
	}
	err = writer.Close()
	if err != nil {
		return nil, err
	}
	request, err := http.NewRequest(http.MethodPost, r.url, body)
	request.Header.Set("Content-Type", writer.FormDataContentType())
	client := &http.Client{}
	response, err := client.Do(request)
	if err != nil {
		return nil, err
	}
	return response, nil
}
